package com.chapp.lastFmWs.parser.base;

import org.xml.sax.Attributes;

import com.chapp.lastFmWs.parser.SearchResponse;

import android.sax.Element;
import android.sax.EndTextElementListener;
import android.sax.StartElementListener;
import android.util.Log;

public abstract class SearchBaseParser<T> extends ResponseParser {

	protected SearchResponse<T> response = new SearchResponse<T>();

	private String tag = this.getClass().getName();
	private String opensearchNamespace = "http://a9.com/-/spec/opensearch/1.1/";
	protected final String geoNamesace = "http://www.w3.org/2003/01/geo/wgs84_pos#";

	protected Element elementResults = rootLmf.getChild("results");

	public abstract SearchResponse<T> parse(String xml);

	// <opensearch:Query role="request" searchTerms="arena" startPage="1"/>
	// <opensearch:totalResults>92</opensearch:totalResults>
	// <opensearch:startIndex>0</opensearch:startIndex>
	// <opensearch:itemsPerPage>50</opensearch:itemsPerPage>

	public SearchBaseParser() {
		Log.d(tag, "serach Constructr");

		elementResults.setStartElementListener(new StartElementListener() {
			@Override
			public void start(Attributes attributes) {
				Log.d(tag, "createlistener");
				createListeners();
				response = new SearchResponse<T>();
				response.setStatusOk(statusOk);
				Log.d(tag, "FINcreatelistener");
			}
		});
	}

	protected void createListeners() {
		Log.d(tag, "init serach parser");

		elementResults.requireChild(opensearchNamespace, "Query")
				.setStartElementListener(new StartElementListener() {
					@Override
					public void start(Attributes attributes) {
						response.setQuery(attributes.getValue("searchTerms"));
					}
				});

		elementResults.requireChild(opensearchNamespace, "totalResults")
				.setEndTextElementListener(new EndTextElementListener() {
					@Override
					public void end(String body) {
						response.setTotalResults(Integer.parseInt(body));
					}
				});
		Log.d(tag, "fin search parser");
	}
}
